var express = require('express');
var router = express.Router();
const fs = require('fs')
const multer = require("multer");
// 引入七牛模块
const qiniu = require('qiniu')
const qnconfig = require('../config/qiniuConfig')
var upload = multer({ dest: "uploads/" }); //本地服务文件夹
 
//单文件
router.post("/upload", upload.single("file"), (req, res, next) => {
    var fileObj = req.file;
    uploadFile(fileObj,(respBody)=>{
        if (respBody){
            res.status(200).json({
                code: "200",
                data: respBody,
                msg: "上传成功",
            });
        }else{
            res.status(400).json({ code: "400", msg: "上传失败" });
        }
    })
});
//多文件
router.post("/files", upload.array("file"), (req, res, next) => {
    var fileObj = req.files;
    var actions = [];
    for (var i =0;i<fileObj.length; i++){
        var action = () =>{
            return new Promise(resolve => {
                uploadFile(fileObj[i], function(respBody) {
                    resolve(respBody);
                });
            })
        }
        actions.push(action());  // 将每次循环调用的方法添加到方法数组中
    }
    Promise.all(actions).then((resolve)=>{
        res.status(200).json({
            code: "200",
            data: resolve,
            msg: "上传成功",
        });
    })
});
 
// 上传函数
function uploadFile(fileObj, callback) {
    var formUploader = new qiniu.form_up.FormUploader(qnconfig.config);
    var putExtra = new qiniu.form_up.PutExtra();
    console.log('fileObj: ',fileObj)
    // 七牛云上的保存位置、本地服务文件的路径
    formUploader.putFile(qnconfig.uploadToken, qnconfig.jwtSecretKey+fileObj.filename, fileObj.path, putExtra)
    .then(({ data, resp }) => {
        if (resp.statusCode === 200) {
            console.log(data);
            const bucketManager = new qiniu.rs.BucketManager(qnconfig.mac, qnconfig.config);
            const publicDownloadUrl = bucketManager.publicDownloadUrl(qnconfig.privateBucketDomain, data.key);
            console.log('publicDownloadUrl', publicDownloadUrl)
            callback(publicDownloadUrl)
        } else {
            console.log(resp.statusCode);
            callback(data);
        }
    })
    .catch(err => {
        console.log('failed', err);
    });
}
module.exports = router;